<?php

include_once('../includes/definer.php');
include_once(INC . 'php/bootstrap.php');
include_once(INC . 'php/clases/FileImage.php');

$relativePath = '../content/tmp/images/';
$ruta = INC . $relativePath;
$response = array();

//obtencion de la imagen
if ($thumb = videoThumb($_POST['video'])) {
    $nombre = $_POST['imgprefix'].'-'.(Imagen::lastId()+1);

    //dimensionamiento y creacion de las imagenes
    $fileImage = new FileImage($thumb, 85);
    if ($fileImage->ancho > 620) $fileImage->ajustarAncho(620);
    $fileImage->save($ruta.$nombre);
    
    $fileImage = new FileImage($thumb, 85);
    $fileImage->escalar(256, 256);
    $fileImage->recortarDesdeElCentro(256, 256);
    $fileImage->watermark(INC.'img/play.png');
    $fileImage->save($ruta . 'thumb/' . $nombre);

    $image = new Imagen();
    $image->src = $nombre . '.' . $fileImage->extension;
    $image->url = urldecode($_POST['video']);
    $image->is_video = 1;
    $image->save();

    //respuesta
    $response[] = array(
        'id' => $image->id,
        'src' => $relativePath . 'thumb/' . $nombre . '.' . $fileImage->extension
    );
} else {
    $response[] = array(
        'error' => 'La url ingresada no es v&aacute;lida. S&oacute;lo se permiten links de vimeo o youtube'
    );
}

header("Content-type: application/json");
echo(json_encode($response));


//funcion para extraer thumbnail
function videoThumb($url) {
    $response;
    if (!filter_var($url, FILTER_VALIDATE_URL))
        $response = false;
    $domain = parse_url($url, PHP_URL_HOST);
    if ($domain == 'www.youtube.com' || $domain == 'youtube.com') { // http://www.youtube.com/watch?v=t7rtVX0bcj8&feature=topvideos_film
        if ($querystring = parse_url($url, PHP_URL_QUERY)) {
            parse_str($querystring);
            $response = (empty($v)) ? false : "http://img.youtube.com/vi/$v/mqdefault.jpg";
        } else {
            $response = false;
        }
    } elseif ($domain == 'youtu.be') { // something like http://youtu.be/t7rtVX0bcj8
        $v = str_replace('/', '', parse_url($url, PHP_URL_PATH));
        $response = (empty($v)) ? false : "http://img.youtube.com/vi/$v/mqdefault.jpg";
    } elseif ($domain == 'vimeo.com') { //vimeo
        $url = str_replace('http://vimeo.com/', 'http://vimeo.com/api/v2/video/', $url) . '.php';
        $html_returned = unserialize(file_get_contents($url));
        $response = $html_returned[0]['thumbnail_large'];
    } else {
        $response = false;
    }
    return $response;
}

?>
